package com.class05.fruit.servlets;



import com.class05.fruit.dao.FruitDAO;
import com.class05.fruit.dao.impl.FruitDAOImpl;
import com.class05.fruit.pojo.Fruit;
import com.class05.myssm.myspringmvc.ViewBaseServlet;
import com.class05.myssm.util.StringUtil;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/index")
public class IndexServlet extends ViewBaseServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
//        获取session主要是为了设置当前页、总页数、每页条数
        HttpSession session = request.getSession();
//        默认加载第一页
        Integer pageNo = 1;
        String oper = request.getParameter("oper");
        String keyword = null;
//        如果oper!=null 说明 通过表单查询按钮点击过来的
//        如果oper是空 比如点击上一页或下一页或者直接在地址栏输入网址加载过来的
        if (StringUtil.isNotEmpty(oper) && "search".equals(oper)){
//     说明 通过表单查询按钮点击过来的请求
            keyword = request.getParameter("keyword");
            if (StringUtil.isEmpty(keyword)){
                keyword = "";
            }
            session.setAttribute("keyword",keyword);
        }else {//点击上一页或下一页或者直接在地址栏输入网址加载过来的
            String pageNoStr = request.getParameter("pageNo");
            if (StringUtil.isNotEmpty(pageNoStr)){
                pageNo = Integer.parseInt(pageNoStr);
            }
//            获取搜索框里面的内容
            Object keywordObj = session.getAttribute("keyword");
            if (keywordObj !=null){
                keyword = (String) keywordObj;
            }else {
                keyword = "";
            }

        }
        session.setAttribute("pageNo",pageNo);
        FruitDAO fruitDAO = new FruitDAOImpl();
        List<Fruit> fruitList = fruitDAO.getFruitList(keyword, pageNo);
        session.setAttribute("fruitList",fruitList);
//        查询总记录数
        int fruitCount = fruitDAO.getFruitCount(keyword);
//        根据总记录数计算总页数
        int pageCount = (fruitCount+5-1)/5;
        session.setAttribute("pageCount",pageCount);
        super.processTemplate("index",request,response);
    }
}
